<script lang="ts" setup>
import type { VbenDrawerInst } from '@vben/common-ui';

import { ElMessage } from 'element-plus';
import { ref, unref } from 'vue';

import { useVbenForm } from '#/adapter/form';
import { resetPassword } from '#/api/system/user';
import { $t } from '#/locales';
import { useResetPasswordFormSchema } from '../data';

const emit = defineEmits(['success', 'register']);

const userId = ref('');
const userName = ref('');
const loading = ref(false);

const [Form, formApi] = useVbenForm({
  submitter: {
    resetButtonOptions: {
      text: $t('ui.common.reset'),
    },
    submitButtonOptions: {
      loading: loading.value,
      text: $t('ui.common.confirm'),
    },
  },
});

// 确认密码验证
const validateConfirmPassword = async (rule, value) => {
  const password = formApi.getFieldValue('newPassword');
  if (password !== value) {
    return Promise.reject(new Error($t('system.user.passwordNotMatch')));
  }
  return Promise.resolve();
};

// 表单模式
const schema = useResetPasswordFormSchema();

// 初始化表单验证规则
formApi.updateSchema([
  {
    fieldName: 'confirmPassword',
    rules: [
      { required: true, message: $t('ui.form.required') },
      { validator: validateConfirmPassword, trigger: 'blur' },
    ],
  },
]);

// 表单提交处理
const handleSubmit = async (values) => {
  try {
    loading.value = true;

    await resetPassword({
      userId: userId.value,
      newPassword: values.newPassword,
      confirmPassword: values.confirmPassword,
    });

    ElMessage.success($t('system.user.resetPasswordSuccess'));
    emit('success');
    closeDrawer();
  } catch (error) {
    console.error('重置密码失败:', error);
    ElMessage.error(error.message || $t('ui.actionMessage.failed'));
  } finally {
    loading.value = false;
  }
};

function closeDrawer() {
  const drawerInstance = unref(drawerDialogRef);
  if (drawerInstance) {
    drawerInstance.closeDrawer();
  }
}

function openDrawer() {
  const drawerInstance = unref(drawerDialogRef);
  if (drawerInstance) {
    drawerInstance.openDrawer();
  }
}

const drawerDialogRef = ref<VbenDrawerInst | null>(null);

function register(instance) {
  drawerDialogRef.value = instance;
  emit('register', instance);
}

// 打开抽屉时的处理
function setData(data) {
  userId.value = data.id || '';
  userName.value = data.userName || '';

  // 重置表单
  formApi.resetFields();

  // 自动打开抽屉
  openDrawer();
}

defineExpose({
  setData,
  open: openDrawer,
  close: closeDrawer,
});
</script>

<template>
  <VbenDrawer
    v-bind="$attrs"
    @register="register"
    :title="$t('system.user.resetPassword')"
    width="500px"
    :onOk="formApi.submit"
    @onClose="formApi.resetFields"
  >
    <div class="mb-4 text-base">
      <span class="font-bold">{{ $t('system.user.userName') }}：</span>
      <span>{{ userName }}</span>
    </div>

    <Form :schema="schema" @submit="handleSubmit" />
  </VbenDrawer>
</template>
